package com.kobeliu.mq;

import com.google.gson.Gson;
import com.kobeliu.api.mq.DelayIndustryConfig;
import com.kobeliu.api.mq.MessageConfig;
import com.kobeliu.pojo.netty.ChatMsg;
import com.kobeliu.service.ArticleService;
import com.kobeliu.service.ChatMessageService;
import com.kobeliu.service.impl.ArticleServiceImpl;
import com.kobeliu.utils.SMSUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ChatMsgConsumer {
    @Autowired
    private ChatMessageService chatMessageService;

    //监听器 监听绑定的队

    @RabbitListener(queues = {MessageConfig.QUEUE_MSG})
    public void watchQueue(Message message, Channel channel) throws Exception {

        System.out.println("++++++++++++++++++++++++++++++++++");
        System.out.println("payLoad:"+new String(message.getBody()));
        System.out.println("+++++++++++++++++++++++++++++++++++");

        try{
            String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
            if(receivedRoutingKey.equalsIgnoreCase(MessageConfig.SAVE_MSG_ROUTING_KEY)){

                ChatMsg chatMsg = new Gson().fromJson(new String(message.getBody()), ChatMsg.class);

                chatMessageService.saveMessage(chatMsg);

                channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);

            }

        }catch (Exception e){
            e.printStackTrace();
            // 消息投递标签
            // 批量确认所有消费真获得的消息
            // requeue 重回队列的策略 true 重回 false丢弃
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
        }

    }
}
